package com.ruike.alisurface.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.cunoraz.gifview.library.GifView;
import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MqttMessageUtils;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.https.AppUpdateHttp;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.ui.settings.BindMachine_Aty;
import com.ruike.alisurface.utils.ShareKey;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_mqtt.MqttService;
import com.voodoo.lib_utils.DeviceUtils;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;

/**
 * 启动页
 */
public class SystemStart_Aty extends BaseAty implements ApiListener {

    @BindView(R.id.systemStart_gifView_gifv)
    GifView showGifv;
    @BindView(R.id.system_sn_code)
    ImageView systemSnCode;
    @BindView(R.id.systemstart_status_tv)
    TextView systemstartStatusTv;
    @BindView(R.id.systemstart_sn_tv)
    TextView systemstartSnTv;

    private String baseUserId = SharedUtils.getInstance().getString(BASEUSERID, "RK_test"); // 用户类型，默认是未分配用户

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x10) {
                systemstartStatusTv.setText("尝试请求中");
                MchApiHttp.getMchBySn(SystemStart_Aty.this); // 获取机器信息
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!this.isTaskRoot() && getIntent() != null) {
            String action = getIntent().getAction();
            if (getIntent().hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                finish();
                return;
            }
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_system_start;
    }

    @Override
    protected void initViews() {
        L.i("机器序列号:" + DeviceUtils.getDeviceSn()
                + "      设备型号:" + Build.MODEL + "      硬件名:" + Build.FINGERPRINT);
        setDataSNcode(systemSnCode);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent("com.MainApp.Action.Start"); // 发送主程序启动的广播
        sendBroadcast(intent);
        showGifv.play();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                systemstartStatusTv.setText("尝试请求中");
                MchApiHttp.getMchBySn(SystemStart_Aty.this); // 获取机器信息
            }
        }, 1000);
    }

    @Override
    protected void initData() {
        setDefultShared(); // 设置Share的默认值
        checkFolder(); // 检查文件夹
//        initDatabases(); // 初始化数据库
        startServices(); // 启动各种服务
        ZXingLibrary.initDisplayOpinion(this);
//        startCountdownTimer(3, null, null); // 开始倒计时
    }

    /**
     * 设置默认Shared值
     */
    private void setDefultShared() {
        // 默认无广告
        if (!SharedUtils.getInstance().containsKey(Constant.AdvType.ADV_TYPE_KEY)) {
            SharedUtils.getInstance().putInt(Constant.AdvType.ADV_TYPE_KEY, Constant.AdvType.NONE);
        }
    }

    /**
     * 检查指定文件夹是否存在
     */
    private void checkFolder() {
        FileUtils.checkFolderIsExists(Constant.FilePath.APK_FOLDER_PATH, true);
        FileUtils.checkFolderIsExists(Constant.FilePath.ADV_IMAGE_FOLDER_PATH, true);
        FileUtils.checkFolderIsExists(Constant.FilePath.ADV_VIDEO_FOLDER_PATH, true);
        FileUtils.checkFolderIsExists(Constant.FilePath.PRODUCT_IMAGE_FOLDER_PATH, true);
        FileUtils.checkFolderIsExists(Constant.FilePath.MAIN_PACKAGE_NAME_FILE_PATH, true);
        FileUtils.checkFolderIsExists(Constant.FilePath.USBIMAGES, true);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mainPackageName", BuildConfig.APPLICATION_ID); // 程序包名

            jsonObject.put("mainPackageType", Constant.APP_TYPE); // 程序类型
            L.i("写入共享文件", "文件地址：" + Constant.FilePath.MAIN_PACKAGE_NAME_FILE_PATH, "写入内容：" + jsonObject.toString());
            FileUtils.writeFileFromString(Constant.FilePath.MAIN_PACKAGE_NAME_FILE_PATH + Constant.FilePath.mainPackageShare1, jsonObject.toString(), false);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 启动各种服务
     */
    private void startServices() {
        startService(new Intent(this, MqttService.class)); // 启动Mqtt服务
    }

    @OnClick({R.id.system_sn_code})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.system_sn_code:
                continuousClick();
                break;
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        showGifv.pause();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith(MchApiHttp.geMchBySn)) {

            String data = requestJson.optString("data");
            try {
                JSONObject dataObject = new JSONObject(data);


                String idStr = dataObject.optString("Id");
                SharedUtils.getInstance().putString(ShareKey.MCH_ID, idStr);
                L.i("onsuccess: MchId：" + idStr);
                String service_tel = dataObject.optString("service_tel");
                if (!service_tel.equals("null") && service_tel != null && !service_tel.isEmpty()) {
                    L.i("===service_tel==" + service_tel);
                    SharedUtils.getInstance().putString(SERVICE_TEL, service_tel);
                } else {
                    SharedUtils.getInstance().putString(SERVICE_TEL, getString(R.string.noPhoneStr));
                }
                baseUserId = dataObject.optString("BaseUserId");
                SharedUtils.getInstance().putString(BASEUSERID, baseUserId);
                L.i("==BaseUserId==" + baseUserId);
                int IC2_max_lattices = dataObject.optInt("IC2_max_lattices");
                L.i("==货道柜设置余数==" + IC2_max_lattices);
                if (IC2_max_lattices > 0) {
                    SharedUtils.getInstance().putInt(IC2_SLOT_NUM, IC2_max_lattices);
                }
                boolean medicine_is_scan = dataObject.optBoolean("medicine_is_scan");
                SharedUtils.getInstance().putBoolean(ShareKey.medicine_is_scan, medicine_is_scan);
                String medicine_scan_alert = dataObject.optString("medicine_scan_alert");
                SharedUtils.getInstance().putString(ShareKey.medicine_scan_alert, medicine_scan_alert);

//            L.i("== 不需要查询版本信息=is_old=" + is_old);
//            Ttys3Utils.getInstance().LEDSetting(10, "0", "1", "1", 15, 15);

                Ttys3Utils.getInstance().getWenKongVersion(6);
                SystemClock.sleep(600);
                Ttys3Utils.getInstance().getQuDongVersion(10);
                AppUpdateHttp.tellServiceAppVersionInfo(this);
                SystemClock.sleep(500);
                ShopApiHttp.get_external_api_parameter(1);
                SystemClock.sleep(500);
                doNext();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

        if (requestUrl.endsWith(MchApiHttp.geMchBySn)) {
            systemstartStatusTv.setText(errorMsg);
            L.i(" 再次尝试请求数据== " + errorMsg);
            handler.sendEmptyMessageDelayed(0x10, 15000);

        }
    }


    /**
     * 下一步
     */
    private void doNext() {
        if (baseUserId.equals("RK_test")) {
            startActivity(BindMachine_Aty.class, null);
            finish();
            return;
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                MqttMessageUtils.getInstance(). sendIccidInfo();
                MqttMessageUtils.getInstance().Beat();
                MqttMessageUtils.getInstance().sendNetInfo();
                startCountdownTimer(0, null, null);
            }
        }, 2000);
    }
}
